<?php

namespace app\lib;

use Qiniu\Storage\BucketManager;
use Yii;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use yii\helpers\Url;

class QiniuHelper {
    const DEAL_IMAGE = "image";

    // 有文件时上传一个文件
    public static function upload($type = 'image', $file) {
        $config = Yii::$app->params['qiniu-key'];
        $auth = new Auth($config['access_key'], $config['secret_key']);

        $params = Yii::$app->params['upload-policy'][$type];
        $bucket = $params['bucket'];
        // 由7牛自动命名
//        $key = md5_file($file);
        $token = $auth->uploadToken($bucket, null);
        $uploadManager = new UploadManager();

        list($ret, $err) = $uploadManager->putFile($token, null, $file);
        if ($err != null) {
            Yii::error("Upload failed, result: " . json_encode($err));
            return null;
        }

        $url = "http://{$params['domain']}/{$ret['key']}";
        return $params + $ret + ['url' => $url];
    }

    // 主动去抓取某一个文件
    public static function fetch($url, $filename = null, $type = 'image') {
        $config = Yii::$app->params['qiniu-key'];
        $auth = new Auth($config['access_key'], $config['secret_key']);

        $params = Yii::$app->params['upload-policy'][$type];

        $bucket = $params['bucket'];

        $bucketManager = new BucketManager($auth);
        list($ret, $err) = $bucketManager->fetch($url, $bucket, "fetch_file" . md5(md5("fetch" . $url)));
        if ($err != null) {
            return [];
        }

        // 原文件名
        if (empty($filename)) {
            $filename = substr($url, strrpos($url, '/') + 1);
            $filename = substr($filename, 0, strrpos($filename, '?'));
        }
        if (empty($filename)) {
            $filename = md5($url);
        }

        $url = "http://{$params['domain']}/{$ret['key']}";
        return $params + $ret + ['url' => $url, 'filename' => $filename];
    }

    // 获取上传token, token就是前端上传的时候，用token才可以往对应的库上传，保证安全性
    protected static function token($params = []) {
        // 读取秘钥，构造验证对象，Auth对象是七牛sdk里面的，就这么用的……
        $config = Yii::$app->params['qiniu-key'];
        $auth = new Auth($config['access_key'], $config['secret_key']);

        // 这个就是刚刚的参数，
        $bucket = $params['bucket'];

        $token = $auth->uploadToken($bucket, null, 3600 * 24);

        return $token;
    }

    // 获取下载token，并设置好回调url
    public static function backBaseApiToken($type = 'image') {
        // 这里就是读取刚刚配置的那个上传策略
        $param = Yii::$app->params['upload-policy'][$type];
        return self::token($param);
    }
}
